<template>
  <avue-crud ref="userRef" :option="option" @refresh-change="getList" :data="data" :cell-style="cellStyle" :page="page"
    @row-save="del_userCtl" @size-change="sizeChange" @current-change="currentChange" @search-change="searchChange"
    @search-reset="searchReset">
    <template #menu="{ row, index, size }">
      <el-button type="primary" text @click="prop_userCtl(row)">删除</el-button>
      <el-button type="primary" text @click="userDetail(row)">修改密码</el-button>
    </template>
  </avue-crud>

  <DetailDialog :visible="detailVisible" v-model="detailVisible" :detailData="detail_data"
    @update:visible="detailVisible = $event" />

  <el-dialog v-model="userDepositVisible" title="手动上分" width="400" :show-close="false">
    <el-form ref="depositFormRef" :model="depositForm" :rules="depositRule" label-width="auto">
      <el-form-item label="用户ID">{{ depositForm.userid }}</el-form-item>
      <el-form-item label="用户名">{{ depositForm.name }}</el-form-item>
      <el-form-item>
        <el-radio-group v-model="userCtlFrom.upctl">
          <el-radio-button label="上分金额"></el-radio-button>
          <el-radio-button label="赠送积分"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="输入值" prop="gold">
        <el-input type="number" v-model="depositForm.gold" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelDeposit(depositFormRef)">取消</el-button>
        <el-button type="primary" @click="confirmDeposit(depositFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="userCtlVisible">
    <el-from ref="form" :model="userCtlFrom">
      <el-form-item>
        <span>用户ID:{{ userCtlFrom.userid }}</span>
      </el-form-item>
      <el-form-item>
        <span>当前状态:{{ userCtlFrom.pagenum }}</span>
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="userCtlFrom.control">
          <el-radio-button label="送"></el-radio-button>
          <el-radio-button label="正常"></el-radio-button>
          <el-radio-button label="杀"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="送分金额" prop="changegold">
        <el-input v-model="userCtlFrom.changegold"></el-input>
      </el-form-item>
    </el-from>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userCtlVisible = false">取消</el-button>
        <el-button type="primary" @click="comit_userCtl(userCtlFrom)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="addDialogVisible" title="新增用户" width="400">
    <el-form :model="newUserForm" label-width="auto">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="newUserForm.name" />
      </el-form-item>
      <el-form-item label="用户ID" prop="userid">
        <el-input v-model="newUserForm.userid" />
      </el-form-item>
      <!-- Add more form items as needed -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUser">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="changePasswordVisible" title="修改密码" width="400">
    <el-form :model="passwordForm" label-width="auto">
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="changePasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmChangePassword">确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import user from "@/options/subAdmin";
import DetailDialog from '@/components/DetailDialog.vue'; // 引入DetailDialog组件
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getUserList,
  markUser,
  SubAdmin_changepwd,
  addUserGold,
  setGamePoint,
  setUserCtl,
  SubAdmin_add,
  SubAdmin_del,
  SubAdmin_list
} from "@/apis/admin";
import { useRouter } from "vue-router";

const userCtlFrom = ref({
  userid: '000',
  control: '送',
  changegold: 0,
  currentchangegold: 0,
  pagenum: 0,
  upctl: '上分金额'
})

// SubAdmin_list.post("", {}).then((res) => {
//   console.log('SubAdmin_list',res)
// })

const router = useRouter();
const depositFormRef = ref(null);
const depositForm = reactive({
  userid: 1,
  name: "",
  gold: "0",
});
const flowUserId = ref("");

const depositRule = reactive({
  gold: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const userDepositVisible = ref(false);
const userCtlVisible = ref(false);
const detailVisible = ref(false);
const addDialogVisible = ref(false);
const changePasswordVisible = ref(false);
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});
const cancelDeposit = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  userDepositVisible.value = false;
};
const confirmDeposit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (userCtlFrom.value.upctl == '上分金额') {
        addUserGold
          .post("", { ...depositForm, gold: depositForm.gold * 100 })
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("上分成功!");
              formEl.resetFields();
              userDepositVisible.value = false;
              getList();
            }
          });
      } else if (userCtlFrom.value.upctl == '赠送积分') {
        setGamePoint
          .post("", { ...depositForm, gold: Number(depositForm.gold) })
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("赠送积分成功!");
              formEl.resetFields();
              userDepositVisible.value = false;
              getList();
            } else {
              ElMessage.error("赠送积分失败!");
              userDepositVisible.value = false;
            }
          });
      } else {
        ElMessage.error("操作失败!");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
onMounted(() => {
  getList();
});
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  getList();
  done();
};
const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  getList();
};

const userDetail = (data) => {
  console.log('userDetail', data)
  flowUserId.value = data.account;
  changePasswordVisible.value = true;
};
const detail_data = ref({});

const option = user;
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
});
const sizeChange = (val) => {
  page.pageSize = val;
  getList();
};
const currentChange = (val) => {
  page.currentPage = val;
  getList();
};
const data = ref([]);
const getList = async () => {
  window.loading(1)
  const res = await SubAdmin_list.post("", {})
  // const res = await getUserList.post("", {
  //   pageSize: page.pageSize,
  //   page: page.currentPage,
  //   searchInfo: page.searchInfo,
  //   orderKey: "created_at",
  //   orderType: "desc",
  // });
  window.loading(0)
  if (res.code == 200) {
    // page.total = res.data.total;
    data.value = res.data.lists || [];
  }
};

const del_userCtl = async (data) => {
  // userCtlVisible.value = true;
  data.level = 1;
  data.status = 2;
  data.inactive = Number(data.inactive)
  let _serverData = await SubAdmin_add.post("", { addUser:{...data} })
  console.log(_serverData)

  this.getList()
}

/**
 * 
 * 删除用户
 */
const prop_userCtl = async (data) => {
  // userCtlVisible.value = true;
  let _serverData = await SubAdmin_del.post("", { account: data.account })
  console.log(_serverData)

  this.getList()
}
const comit_userCtl = (data) => {
  console.log(data)
  window.loading(1)
  let control = 0;//正常
  if (data.control == '正常') {
    control = 0
  } else if (data.control == '杀') {
    control = 2
    if (Number(data.changegold) > 0) {
      data.changegold = -Number(data.changegold)
    }
  } else {
    control = 1
    if (Number(data.changegold) < 0) {
      data.changegold = Math.abs(Number(data.changegold))
    }
  }
  if (isNaN(Number(data.changegold))) {
    data.changegold = 0;
  }
  setUserCtl.post("", { userId: data.userid, control: control, changegold: Number(data.changegold) * 100 }).then((res) => {
    if (res.code == 200) {
      ElMessage.success("修改成功!");
    }
    window.loading(0)
    userCtlVisible.value = false;

  });
}

const newUserForm = reactive({
  name: '',
  userid: '',
  // Initialize other fields as needed
});

const confirmAddUser = () => {
  // Logic to handle adding a new user
  console.log('Adding user:', newUserForm);
  // Reset form and close dialog
  Object.keys(newUserForm).forEach(key => newUserForm[key] = '');
  addDialogVisible.value = false;
};

const confirmChangePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error("两次输入的密码不一致！");
    return;
  }

  try {
    const response = await SubAdmin_changepwd.post("", {
      account: flowUserId.value,
      new_pwd: passwordForm.newPassword
    });

    if (response.code === 200) {
      ElMessage.success("密码修改成功！");
      // Reset form and close dialog
      passwordForm.newPassword = '';
      passwordForm.confirmPassword = '';
      changePasswordVisible.value = false;
    } else {
      ElMessage.error("密码修改失败！");
    }
  } catch (error) {
    ElMessage.error("请求失败，请稍后重试！");
    console.error("Error changing password:", error);
  }
};
</script>
<style lang="scss" scoped>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.subtitle {
  width: 100%;
  border-radius: 4px;
  background: #f5f5f5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  box-sizing: border-box;
  padding: 8px 10px;
  margin: 10px 0;
}

.label {
  color: #666;
  font-size: 12px;
  padding-right: 8px;
}

.value {
  color: #333;
  font-size: 13px;
}
</style>
